/**
 * @Description 社会实践实现层
 * @author 20155870 杨润增
 * @create 2018-05-24 15:13
 **/
package com.campus_information_portal.service.impl;

import com.campus_information_portal.dao.ProjectDao;
import com.campus_information_portal.entity.Project;
import com.campus_information_portal.entity.ProjectStudent;
import com.campus_information_portal.service.ProjectService;
import com.campus_information_portal.service.TermService;
import com.campus_information_portal.util.DateUtil;
import com.campus_information_portal.util.Message;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 20155870 杨润增
 * @className ProjectImpl
 * @Description 社会实践实现层
 * @create 2018-05-24 15:13
 **/
@Service
public class ProjectImpl implements ProjectService {
    @Autowired
    private ProjectDao projectDao;


    @Override
    public Message addProject(int termId, int stuInfoId, String projectName, String projectContent,
                              String projectPhonenum, Date projectStartDate, Date projectEndDate,
                              String projectContactPeople, String projectPlatform, int projectState) {
        Project project = new Project();
        project.setProjectContactPeople(projectContactPeople);
        project.setProjectContent(projectContent);
        project.setProjectEndtDate(projectEndDate);
        project.setProjectName(projectName);
        project.setProjectPhonenum(projectPhonenum);
        project.setProjectPlatform(projectPlatform);
        project.setProjectStartDate(projectStartDate);
        project.setStuInfoId(stuInfoId);
        project.setTermId(termId);
        project.setProjectState(projectState);

        int count = projectDao.queryCountProject(stuInfoId, termId);
        int can = projectDao.canApplyProject(stuInfoId, termId);

        if (count == 1) {
            return Message.fail().add("0801", "这学期已经申请通过啦！请不要重复申请！");
        } else if (can > 0) {
            return Message.fail().add("0801", "你的申请等待批准！请不要重复申请！");
        } else {
            int flag = projectDao.addProject(project);
            if (flag == 1) {
                return Message.success();
            } else
                return Message.fail().add("0801", "添加失败");
        }
    }

    @Override
    public Message deleteProject(int projectId) {
        if (projectId > 0) {
            int flag = projectDao.deleteProject(projectId);
            if (flag == 1) {
                return Message.success();
            } else
                return Message.fail().add("0802", "删除失败");
        }
        return Message.fail().add("0802", "id不存在,删除失败");
    }

    @Override
    public Message queryAllProject() {
        List<ProjectStudent> projectList = projectDao.queryAllProject();
        if (projectList != null) {
            return Message.success().add("projectList", projectList);
        }
        return Message.fail().add("0803", "没有数据或查询失败");
    }

    @Override
    public Message queryMyProject(int stuNum) {
        List<ProjectStudent> projectList = projectDao.queryMyProject(stuNum);
        if (projectList != null) {
            return Message.success().add("projectList", projectList);
        }
        return Message.fail().add("0803", "没有数据或查询失败");
    }

    @Override
    public Message updateProjectstate(int projectId, int projectState) {
        int flag = 0;
        if (projectId > 0) {
            if (projectState == 0) {
                flag = projectDao.updateProject(projectId, projectState);
                if (flag==1){
                    return Message.success();
                }else
                    return Message.fail().add("0804","更新失败");
            }else if(projectState==1){
                flag = projectDao.updateProject(projectId, projectState);
                if (flag==1){
                    return Message.success();
                }else
                    return Message.fail().add("0804","更新失败");
            }
        }
        return Message.fail().add("0804","更新失败");
    }

    @Override
    public Message updateAProject(Project project) {
        System.out.println(project);
        if (project != null) {
            int projectId = project.getProjectId();
            String projectName = project.getProjectName();
            String projectContent = project.getProjectContent();
            String projectPhonenum = project.getProjectPhonenum();
            Date projectStartDate = project.getProjectStartDate();
            Date projectEndtDate = project.getProjectEndtDate();
            String projectContactPeople = project.getProjectContactPeople();
            String projectPlatform = project.getProjectPlatform();

            int flag = projectDao.updateMyProject(projectId, projectName, projectContent, projectPhonenum,
                    projectStartDate, projectEndtDate, projectContactPeople, projectPlatform);
            if (flag == 1) {
                return Message.success();
            } else
                return Message.fail().add("0804", "更新失败");
        }
        return Message.fail().add("0804", "数据为空");
    }

    @Override
    public Message queryProjectById(int projectId) {
        if (projectId > 0) {
            ProjectStudent projectStudent = projectDao.queryProjectById(projectId);
            if (projectStudent != null) {
                return Message.success().add("projectStudent", projectStudent);
            }
            return Message.fail().add("0805", "没有数据");
        }
        return Message.fail().add("0805", "projectId错误");
    }

    public Message download(int stuNum, String stuName, String stuSex, String academyName,
                            String termYear, String termNum, String startDate, String endDate,
                            String contact, String contactPhone, String platform, String proName,
                            String proContent) throws UnknownHostException {
        // 模板路径.最终放在服务器下。远程即可访问
        String templatePath = "F:/专业设计/sjb.pdf";
        // 生成的新文件路径
        //首先获取获取本机计算机名称
        InetAddress addr = InetAddress.getLocalHost();
        String hostName = addr.getHostName().toString();
        //保存在桌面上
        String newPDFPath = "C:/Users/" + hostName + "/Desktop/华信大学暑期社会实践表_" + stuName + ".pdf";


        PdfReader reader;
        FileOutputStream out;
        ByteArrayOutputStream bos;
        PdfStamper stamper;

        try {
            out = new FileOutputStream(newPDFPath);// 输出流
            reader = new PdfReader(templatePath);// 读取pdf模板
            bos = new ByteArrayOutputStream();
            stamper = new PdfStamper(reader, bos);
            AcroFields form = stamper.getAcroFields();

            Map<String, Object> barcodeFields = new HashMap<String, Object>();
            barcodeFields.put("ifLogic", DateUtil.toString(new Date()));
            //遍历条码字段
            for (Map.Entry<String, Object> entry : barcodeFields.entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();
                // 获取属性的类型
                if(value != null && form.getField(key) != null){
                    //获取位置(左上右下)
                    AcroFields.FieldPosition fieldPosition = form.getFieldPositions(key).get(0);
                    //绘制条码
                    Barcode39 barcode39 = new Barcode39();
                    //字号
                    barcode39.setSize(12);
                    //条码高度
                    barcode39.setBarHeight(30);
                    //条码与数字间距
                    barcode39.setBaseline(10);
                    //条码值
                    barcode39.setCode(value.toString());
                    barcode39.setStartStopText(false);
                    barcode39.setExtended(true);
                    //绘制在第一页
                    PdfContentByte cb = stamper.getOverContent(1);
                    //生成条码图片
                    Image image128 = barcode39.createImageWithBarcode(cb, null, null);
                    //左边距(居中处理)
                    float marginLeft = (fieldPosition.position.getRight() - fieldPosition.position.getLeft() - image128.getWidth()) / 2;
                    //条码位置
                    image128.setAbsolutePosition(fieldPosition.position.getLeft() + marginLeft, fieldPosition.position.getBottom());
                    //加入条码
                    cb.addImage(image128);
                }
            }

            Map<String, Object> qrcodeFields = new HashMap<String, Object>();
            qrcodeFields.put("qrCode","学号："+stuNum+"姓名："+stuName);
            //遍历二维码字段
            for (Map.Entry<String, Object> entry : qrcodeFields.entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();
                // 获取属性的类型
                if(value != null && form.getField(key) != null){
                    //获取位置(左上右下)
                    AcroFields.FieldPosition fieldPosition = form.getFieldPositions(key).get(0);
                    //绘制二维码
                    float width = fieldPosition.position.getRight() - fieldPosition.position.getLeft();
                    BarcodeQRCode pdf417 = new BarcodeQRCode(value.toString(), (int)width, (int)width, null);
                    //生成二维码图像
                    Image image128 = pdf417.getImage();
                    //绘制在第一页
                    PdfContentByte cb = stamper.getOverContent(1);
                    //左边距(居中处理)
                    float marginLeft = (fieldPosition.position.getRight() - fieldPosition.position.getLeft() - image128.getWidth()) / 2;
                    //条码位置
                    image128.setAbsolutePosition(fieldPosition.position.getLeft() + marginLeft, fieldPosition.position.getBottom());
                    //加入条码
                    cb.addImage(image128);
                }
            }
            //设置表单域的内容
            form.setField("fill_1", stuNum + "");
            form.setField("fill_2", stuName);
            form.setField("fill_3", stuSex);
            form.setField("fill_4", academyName);
            form.setField("fill_5", termYear);
            form.setField("fill_6", termNum);
            form.setField("fill_7", proName);
            form.setField("fill_8", startDate);
            form.setField("fill_9", endDate);
            form.setField("fill_10", academyName);
            form.setField("fill_11", contact);
            form.setField("fill_12", contactPhone);
            form.setField("fill_13", platform);
            form.setField("fill_14", proContent);
            form.setField("fill_15", DateUtil.toString(new Date(), "yyyy-MM-dd"));
            // 如果为false那么生成的PDF文件还能编辑，一定要设为true
            stamper.setFormFlattening(true);
            stamper.close();
            Document doc = new Document();
            PdfCopy copy = new PdfCopy(doc, out);
            doc.open();
            PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
            copy.addPage(importPage);
            doc.close();
            reader.close();

        } catch (IOException e) {
            System.out.println(1);
        } catch (DocumentException e) {
            System.out.println(2);
        }
        return Message.success();
    }
}
